package com.caiyi.tips.core.util;


import org.apache.commons.codec.digest.DigestUtils;

import java.lang.management.ManagementFactory;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

public class IdCreator {
    private IdCreator() {
        throw new RuntimeException("不允许构造");
    }

    private final static String YOUYU_NICKID_PREFIX = youyuNickIdPrefix();


    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }


    private static int startNextValue = ThreadLocalRandom.current().nextInt(10000, 99999);

    /**
     * 生成临时有鱼用户名
     *
     * @return
     */
    public static String youyuNickId() {
        int i = 0;
        synchronized (IdCreator.class) {
            if (startNextValue > 99999) {
                startNextValue = ThreadLocalRandom.current().nextInt(10000, 99999);
            }
            i = startNextValue++;
        }
        return YOUYU_NICKID_PREFIX + System.currentTimeMillis() + i;
    }

    private static String youyuNickIdPrefix() {

        Enumeration allNetInterfaces = null;
        String ipAddr = null;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();

                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = (InetAddress) addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address) {
                        String ipStr = ip.getHostAddress();
                        if (ipStr.indexOf("127") != 0) {
                            ipAddr = ipStr;
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }


        String jvmName = ManagementFactory.getRuntimeMXBean().getName();
        String prefix = ipAddr + jvmName.substring(0, jvmName.indexOf("@"));
        prefix = "yu" + DigestUtils.md5Hex(prefix).substring(8, 24);
        return prefix;
    }


}
